import { routerConfig } from "@/router/config"
import { registerNavigationGuard } from "@/router/guard"
import type { RouteRecordRaw } from "vue-router"
import { createRouter } from "vue-router"
import { flatMultiLevelRoutes } from "./helper"
import { systemRoutes } from "./modules/system"
import { samplesRoutes } from "./modules/samples"
import { othersRoutes } from "./modules/others"
import { permissionsRoutes } from "./modules/permissions"
import { ofdRouters } from "./modules/ofdRouters"

const Layouts = () => import("@/layouts/index.vue")

/**
 * @name 常驻路由
 * @description 除了 redirect/403/404/login 等隐藏页面，其他页面建议设置唯一的 Name 属性
 */
export const constantRoutes: RouteRecordRaw[] = [
  ...ofdRouters,
  ...systemRoutes,
  //...samplesRoutes,
  //...othersRoutes
]

/**
 * @name 动态路由
 * @description 用来放置有权限 (Roles 属性) 的路由
 * @description 必须带有唯一的 Name 属性
 */
export const dynamicRoutes: RouteRecordRaw[] = [
  //...permissionsRoutes
]

/** 路由实例 */
export const router = createRouter({
  history: routerConfig.history,
  routes: routerConfig.thirdLevelRouteCache ? flatMultiLevelRoutes(constantRoutes) : constantRoutes
})

/** 重置路由 */
export function resetRouter() {
  try {
    // 注意：所有动态路由路由必须带有 Name 属性，否则可能会不能完全重置干净
    router.getRoutes().forEach((route) => {
      const { name, meta } = route
      if (name && meta.roles?.length) {
        router.hasRoute(name) && router.removeRoute(name)
      }
    })
  } catch {
    // 强制刷新浏览器也行，只是交互体验不是很好
    location.reload()
  }
}

// 注册路由导航守卫
registerNavigationGuard(router)
